package cn.molu.jsoup.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author 陌路
 * @apiNote 项目启动后和关闭后置处理
 * @date 2024/1/16 14:00
 * @tool Created by IntelliJ IDEA
 */
@Slf4j
@Component
public class ServerRunnerAndDisposable implements ApplicationRunner, DisposableBean {

    @Value("${server.port}")
    private String port;

    /**
     * 项目启动时执行
     *
     * @param args 启动参数
     */
    @Override
    public void run(ApplicationArguments args) {
        printInfo("==============项目启动成功！==============");
        printInfo("请访问地址：http://{}:{}/{}", getHostIp(), port, "api/v1/parseHtml/query/%E7%BE%8E%E5%A5%B3");
        printInfo("=======================================");
    }

    /**
     * 项目关闭时执行
     */
    @Override
    public void destroy() {
        printInfo("=======================================");
        printInfo("=============程序已停止运行！=============");
        printInfo("=======================================");
    }

    /**
     * 获取服务IP
     */
    public String getHostIp() {
        final String LOCAL_IP = "127.0.0.1";
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String ip = localHost.getHostAddress();
            return StrUtil.isEmpty(ip) ? LOCAL_IP : ip;
        } catch (UnknownHostException ignored) {
        }
        return LOCAL_IP;
    }

    /**
     * 打印信息
     *
     * @param template 模板
     * @param args     参数
     */
    private void printInfo(String template, Object... args) {
        if (StrUtil.isNotBlank(template)) {
            if (null != args && args.length > 0) {
                System.out.printf(template.replaceAll("\\{}", "%s"), args);
                System.out.println();
            } else {
                System.out.println(template);
            }
        }
    }
}